package com.hkrt.demo.zip;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Surpass
 * @Package com.hkrt.demo.zip
 * @Description: 单文件压缩
 * @date 2020/10/16 10:51
 */
public class SingleZipCompression {

    private static InputStream inputStream;
    private static ZipOutputStream zipOutputStream;
    private static OutputStream outputStream;
    private static String filePath = "C:\\Users\\Surpass\\Desktop\\Linux就该这么学 高清晰PDF.pdf";

    public static void main(String[] args)  {
        try {
            //文件输入流
            File file = new File(filePath);
            inputStream = new FileInputStream(file);

            //压缩输出路径的流   压缩文件路径+压缩文件名前缀（Linux就该这么学 高清晰PDF）+.zip
            outputStream = new FileOutputStream(file.getParent()+"\\"+file.getName().substring(0,file.getName().lastIndexOf("."))+".zip");
            zipOutputStream = new ZipOutputStream(outputStream);

            //压缩包内文件的名字   Linux就该这么学 高清晰PDF.pdf
            zipOutputStream.putNextEntry(new ZipEntry(file.getName()));

            //输出文件
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes))!=-1){
                zipOutputStream.write(bytes,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (zipOutputStream!=null){
                    zipOutputStream.closeEntry();
                    zipOutputStream.close();
                }
                if (outputStream!=null){
                    outputStream.close();
                }
                if (inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
